﻿namespace Auros.EPiSiteMap.Filters
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using EPiServer.Filters;

    internal class FilterLocator
    {
        /// <summary>
        ///   Locates the filters to be used in sitemap generation.
        /// </summary>
        internal static IEnumerable<IPageFilter> GetSitemapFilters()
        {
            // Get the filters by looking at all types which implement IPageFilter
            var filters = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes()
                    .Where(type => typeof(IPageFilter).IsAssignableFrom(type)));

            // Limit to the types which are decorated with the SitemapFilterAttrbiute.
            var sitemapFilters = filters.Where(filter => filter.GetCustomAttributes(typeof(SiteMapFilter), false).Count() > 0);            
            
            return sitemapFilters.Select(type => Activator.CreateInstance(type) as IPageFilter);
        }
    }
}